package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.entity.VipOrder;
import com.yuelao.yuelao_backend.entity.VipPlan;
import com.yuelao.yuelao_backend.mapper.UserMapper;
import com.yuelao.yuelao_backend.mapper.VipOrderMapper;
import com.yuelao.yuelao_backend.mapper.VipPlanMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.CoinService;
import com.yuelao.yuelao_backend.service.VipService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * VIP Service实现类
 */
@Service
public class VipServiceImpl extends ServiceImpl<VipPlanMapper, VipPlan> implements VipService {

    @Resource
    private VipOrderMapper vipOrderMapper;
    
    @Resource
    private UserMapper userMapper;
    
    @Resource
    private CoinService coinService;
    
    @Resource
    private AchievementService achievementService;

    @Override
    public List<Map<String, Object>> getBenefits() {
        List<Map<String, Object>> benefits = new ArrayList<>();

        benefits.add(createBenefit("👀", "谁喜欢我", "查看所有喜欢你的人"));
        benefits.add(createBenefit("❤️", "超级喜欢", "让对方立刻看到你"));
        benefits.add(createBenefit("🔄", "无限喜欢", "右滑次数无限制"));
        benefits.add(createBenefit("🚀", "曝光提升", "资料被优先推荐"));
        benefits.add(createBenefit("🎯", "高级筛选", "更精准的匹配"));
        benefits.add(createBenefit("🌟", "VIP任务", "专属任务加速成长"));
        benefits.add(createBenefit("🛡️", "尊贵身份标识", "昵称旁专属V标"));
        benefits.add(createBenefit("🚫", "免广告打扰", "享受纯净体验"));
        benefits.add(createBenefit("💰", "爱心币交易特权", "开放用户间交易"));
//        benefits.add(createBenefit("👁️", "隐身模式", "浏览时不留痕迹"));

        return benefits;
    }

    @Override
    public List<VipPlan> getPlans() {
        LambdaQueryWrapper<VipPlan> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(VipPlan::getSortOrder);
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> purchaseVip(Long userId, Long planId, String paymentMethod) {
        // 1. 获取用户和套餐信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }
        
        VipPlan plan = getById(planId);
        if (plan == null) {
            throw new BizException(ErrorCode.NOT_FOUND_ERROR, "VIP套餐不存在或已下架");
        }

        // 2. 根据支付方式处理
        if ("coin".equals(paymentMethod)) {
            // 使用爱心币购买
            Integer coinPrice = plan.getCoinPrice();
            if (coinPrice == null || coinPrice <= 0) {
                throw new BizException(ErrorCode.OPERATION_ERROR, "该套餐不支持爱心币购买");
            }
            
            // 扣除爱心币
            coinService.spendCoins(
                userId, 
                coinPrice,
                "vip_purchase",
                "购买VIP会员",
                "购买" + plan.getName(),
                planId,
                "vip_plan"
            );
        } else {
            // 第三方支付（微信/支付宝）
            // TODO: 集成支付服务
            throw new BizException(ErrorCode.OPERATION_ERROR, "暂不支持该支付方式");
        }

        // 3. 创建订单
        VipOrder order = new VipOrder();
        order.setUserId(userId);
        order.setPlanId(planId);
        order.setAmount(plan.getPrice());
        order.setPaymentMethod(paymentMethod);
        order.setStatus(1); // 已支付
        order.setPaidAt(LocalDateTime.now());
        order.setStartTime(LocalDateTime.now());
        order.setEndTime(LocalDateTime.now().plusDays(plan.getDuration()));
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        vipOrderMapper.insert(order);

        // 4. 更新用户VIP状态
        user.setIsVip(true);
        LocalDateTime newExpireTime;
        if (user.getVipExpireTime() != null && user.getVipExpireTime().isAfter(LocalDateTime.now())) {
            // 如果当前VIP未过期，在原有基础上延长
            newExpireTime = user.getVipExpireTime().plusDays(plan.getDuration());
        } else {
            // 如果已过期或首次购买
            newExpireTime = LocalDateTime.now().plusDays(plan.getDuration());
        }
        user.setVipExpireTime(newExpireTime);
        userMapper.updateById(user);

        // 5. 检查VIP相关成就
        achievementService.checkVipAchievements(userId);

        // 6. 返回订单信息
        Map<String, Object> result = new HashMap<>();
        result.put("order_no", order.getId().toString());
        result.put("plan_name", plan.getName());
        result.put("expire_time", newExpireTime);
        
        return result;
    }

    private Map<String, Object> createBenefit(String icon, String title, String desc) {
        Map<String, Object> benefit = new HashMap<>();
        benefit.put("icon", icon);
        benefit.put("title", title);
        benefit.put("desc", desc);
        return benefit;
    }
}

